<template>
  <div class="interest-preferences">
    <h2 class="preferences-title">兴趣偏好设置</h2>
    
    <!-- 兴趣标签选择 -->
    <div class="preferences-section">
      <h3 class="section-title">天文兴趣标签</h3>
      <p class="section-description">选择您感兴趣的天文现象，我们将为您推荐相关事件</p>
      
      <div class="tag-selection">
        <label 
          v-for="tag in availableTags" 
          :key="tag.id"
          class="tag-option"
        >
          <input 
            type="checkbox" 
            :value="tag.name" 
            v-model="selectedTags"
            @change="updateRecommendations"
          />
          <span class="tag-label">{{ tag.name }}</span>
        </label>
      </div>
    </div>
    
    <!-- 事件类型偏好 -->
    <div class="preferences-section">
      <h3 class="section-title">事件类型偏好</h3>
      <p class="section-description">调整不同类型天文事件的优先级</p>
      
      <div class="event-type-preferences">
        <div 
          v-for="type in availableEventTypes" 
          :key="type.value"
          class="event-type-item"
        >
          <div class="event-type-info">
            <span class="event-type-label">{{ type.label }}</span>
            <span class="event-type-priority">{{ getPriorityLabel(getEventTypePriority(type.value)) }}</span>
          </div>
          <div class="priority-slider">
            <input 
              type="range" 
              :min="1" 
              :max="5" 
              :value="getEventTypePriority(type.value)"
              @input="setEventTypePriority(type.value, $event.target.value)"
              class="slider"
            />
          </div>
        </div>
      </div>
    </div>
    
    <!-- 观测经验级别 -->
    <div class="preferences-section">
      <h3 class="section-title">观测经验</h3>
      <p class="section-description">选择您的天文观测经验级别</p>
      
      <div class="experience-levels">
        <label 
          v-for="level in experienceLevels" 
          :key="level.value"
          class="experience-option"
        >
          <input 
            type="radio" 
            :value="level.value" 
            v-model="experienceLevel"
            @change="updateRecommendations"
          />
          <div class="experience-info">
            <span class="experience-icon">{{ level.icon }}</span>
            <span class="experience-label">{{ level.label }}</span>
          </div>
        </label>
      </div>
    </div>
    
    <!-- 推荐预览 -->
    <div class="preferences-section">
      <h3 class="section-title">基于您的偏好推荐</h3>
      <p class="section-description">根据您的兴趣设置，以下是即将到来的天文事件推荐</p>
      
      <div v-if="recommendedEvents.length > 0" class="recommended-events">
        <div 
          v-for="event in recommendedEvents" 
          :key="event.id"
          class="recommended-event"
          :class="`event-type-${event.type}`"
        >
          <div class="event-date">{{ formatDate(event.date) }}</div>
          <div class="event-title">{{ event.title }}</div>
          <div class="event-tags">
            <span 
              v-for="tag in event.tags" 
              :key="tag" 
              class="event-tag"
              :class="{ 'matched-tag': isTagInSelected(event.tags) }"
            >
              #{{ tag }}
            </span>
          </div>
        </div>
      </div>
      <div v-else class="no-recommendations">
        <p>目前没有符合您兴趣的推荐事件，请尝试调整您的兴趣设置</p>
      </div>
    </div>
    
    <!-- 操作按钮 -->
    <div class="preferences-actions">
      <button class="secondary-button" @click="resetToDefaults">重置为默认值</button>
      <button class="primary-button" @click="savePreferences">保存偏好设置</button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import astronomicalEvents, { getEventTypes, getAllTags } from '../data/astronomicalEvents';
import { getUpcomingEvents } from '../data/astronomicalEvents';

// 可用的兴趣标签
const availableTags = computed(() => {
  const allTags = getAllTags();
  return allTags.map((tag, index) => ({ id: index + 1, name: tag }));
});

// 可用的事件类型
const availableEventTypes = computed(() => getEventTypes());

// 经验级别选项
const experienceLevels = [
  { value: 'beginner', label: '初学者', icon: '🌱' },
  { value: 'intermediate', label: '中级', icon: '📚' },
  { value: 'advanced', label: '高级', icon: '🔭' },
  { value: 'expert', label: '专家', icon: '✨' }
];

// 用户选择的标签
const selectedTags = ref([]);

// 事件类型优先级
const eventTypePriorities = ref({});

// 经验级别
const experienceLevel = ref('beginner');

// 推荐事件
const recommendedEvents = ref([]);

// 初始化
onMounted(() => {
  loadPreferences();
  updateRecommendations();
});

// 加载用户偏好设置
const loadPreferences = () => {
  try {
    // 加载标签偏好
    const savedTags = localStorage.getItem('userInterestTags');
    if (savedTags) {
      selectedTags.value = JSON.parse(savedTags);
    } else {
      // 默认选择一些标签
      selectedTags.value = ['高可见度', '推荐观测'];
    }
    
    // 加载事件类型优先级
    const savedPriorities = localStorage.getItem('eventTypePriorities');
    if (savedPriorities) {
      eventTypePriorities.value = JSON.parse(savedPriorities);
    } else {
      // 设置默认优先级
      availableEventTypes.value.forEach(type => {
        eventTypePriorities.value[type.value] = 3; // 默认中等优先级
      });
    }
    
    // 加载经验级别
    const savedExperience = localStorage.getItem('userExperienceLevel');
    if (savedExperience) {
      experienceLevel.value = savedExperience;
    }
  } catch (error) {
    console.error('加载偏好设置失败:', error);
    // 设置默认值
    selectedTags.value = ['高可见度', '推荐观测'];
    experienceLevel.value = 'beginner';
  }
};

// 保存偏好设置
const savePreferences = () => {
  try {
    localStorage.setItem('userInterestTags', JSON.stringify(selectedTags.value));
    localStorage.setItem('eventTypePriorities', JSON.stringify(eventTypePriorities.value));
    localStorage.setItem('userExperienceLevel', experienceLevel.value);
    
    // 显示保存成功提示
    alert('偏好设置已保存！');
  } catch (error) {
    console.error('保存偏好设置失败:', error);
    alert('保存失败，请重试。');
  }
};

// 重置为默认值
const resetToDefaults = () => {
  if (confirm('确定要重置所有偏好设置为默认值吗？')) {
    selectedTags.value = ['高可见度', '推荐观测'];
    experienceLevel.value = 'beginner';
    
    // 重置事件类型优先级
    availableEventTypes.value.forEach(type => {
      eventTypePriorities.value[type.value] = 3;
    });
    
    updateRecommendations();
  }
};

// 获取事件类型优先级
const getEventTypePriority = (type) => {
  return eventTypePriorities.value[type] || 3;
};

// 设置事件类型优先级
const setEventTypePriority = (type, priority) => {
  eventTypePriorities.value[type] = parseInt(priority);
  updateRecommendations();
};

// 获取优先级标签
const getPriorityLabel = (priority) => {
  const labels = ['', '很低', '低', '中', '高', '很高'];
  return labels[priority] || '中';
};

// 检查标签是否在用户选择中
const isTagInSelected = (eventTags) => {
  return eventTags.some(tag => selectedTags.value.includes(tag));
};

// 更新推荐事件
const updateRecommendations = () => {
  // 获取未来90天的事件
  const upcomingEvents = getUpcomingEvents(90);
  
  // 计算每个事件的匹配分数
  const scoredEvents = upcomingEvents.map(event => {
    let score = 0;
    
    // 根据标签匹配加分
    event.tags.forEach(tag => {
      if (selectedTags.value.includes(tag)) {
        score += 10;
      }
    });
    
    // 根据事件类型优先级加分
    const typePriority = getEventTypePriority(event.type);
    score += typePriority * 5;
    
    // 根据观测经验调整分数
    if (experienceLevel.value === 'beginner' && event.tags.includes('高可见度')) {
      score += 8;
    }
    
    return { ...event, score };
  });
  
  // 按分数排序并取前10个
  recommendedEvents.value = scoredEvents
    .sort((a, b) => b.score - a.score)
    .slice(0, 10);
};

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString);
  return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`;
};
</script>

<style scoped>
.interest-preferences {
  width: 100%;
  max-width: 1000px;
  margin: 0 auto;
  padding: 2rem;
  color: #ffffff;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.preferences-title {
  font-size: 2rem;
  margin-bottom: 2rem;
  color: #4a9eff;
  text-align: center;
}

.preferences-section {
  background-color: rgba(255, 255, 255, 0.05);
  border-radius: 12px;
  padding: 1.5rem;
  margin-bottom: 2rem;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.section-title {
  font-size: 1.5rem;
  margin-bottom: 0.5rem;
  color: #ffffff;
}

.section-description {
  color: rgba(255, 255, 255, 0.7);
  margin-bottom: 1.5rem;
}

/* 标签选择样式 */
.tag-selection {
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
}

.tag-option {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.tag-option input[type="checkbox"] {
  margin-right: 0.5rem;
  width: 18px;
  height: 18px;
  accent-color: #4a9eff;
}

.tag-label {
  font-size: 1rem;
  transition: color 0.2s;
}

.tag-option:hover .tag-label {
  color: #4a9eff;
}

/* 事件类型优先级样式 */
.event-type-preferences {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.event-type-item {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.event-type-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.event-type-label {
  font-weight: 500;
}

.event-type-priority {
  color: #4a9eff;
  font-size: 0.9rem;
}

.priority-slider {
  width: 100%;
}

.slider {
  width: 100%;
  height: 8px;
  border-radius: 4px;
  background: rgba(255, 255, 255, 0.2);
  outline: none;
  cursor: pointer;
}

.slider::-webkit-slider-thumb {
  appearance: none;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background: #4a9eff;
  cursor: pointer;
  transition: transform 0.2s;
}

.slider::-webkit-slider-thumb:hover {
  transform: scale(1.2);
}

/* 经验级别样式 */
.experience-levels {
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
}

.experience-option {
  display: flex;
  align-items: center;
  cursor: pointer;
  background-color: rgba(255, 255, 255, 0.1);
  padding: 1rem;
  border-radius: 8px;
  transition: all 0.2s;
  min-width: 120px;
  justify-content: center;
}

.experience-option:hover {
  background-color: rgba(255, 255, 255, 0.15);
}

.experience-option input[type="radio"] {
  margin-right: 0.8rem;
  width: 18px;
  height: 18px;
  accent-color: #4a9eff;
}

.experience-info {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.experience-icon {
  font-size: 1.2rem;
}

/* 推荐事件样式 */
.recommended-events {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.recommended-event {
  background-color: rgba(255, 255, 255, 0.1);
  padding: 1rem;
  border-radius: 8px;
  border-left: 4px solid #4a9eff;
  transition: transform 0.2s;
}

.recommended-event:hover {
  transform: translateX(5px);
}

.recommended-event.event-type-meteor_shower {
  border-left-color: #ff6b6b;
}

.recommended-event.event-type-lunar_eclipse,
.recommended-event.event-type-solar_eclipse {
  border-left-color: #ffa502;
}

.recommended-event.event-type-planetary_opposition,
.recommended-event.event-type-planetary_configuration {
  border-left-color: #2ed573;
}

.event-date {
  font-size: 0.9rem;
  color: rgba(255, 255, 255, 0.7);
  margin-bottom: 0.5rem;
}

.event-title {
  font-weight: 600;
  font-size: 1.1rem;
  margin-bottom: 0.8rem;
}

.event-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
}

.event-tag {
  font-size: 0.8rem;
  background-color: rgba(255, 255, 255, 0.1);
  padding: 0.3rem 0.6rem;
  border-radius: 20px;
  color: rgba(255, 255, 255, 0.8);
}

.event-tag.matched-tag {
  background-color: rgba(74, 158, 255, 0.3);
  color: #4a9eff;
  font-weight: 500;
}

.no-recommendations {
  text-align: center;
  padding: 2rem;
  color: rgba(255, 255, 255, 0.5);
}

/* 操作按钮样式 */
.preferences-actions {
  display: flex;
  justify-content: center;
  gap: 1rem;
  margin-top: 2rem;
}

.primary-button,
.secondary-button {
  padding: 0.8rem 2rem;
  border: none;
  border-radius: 6px;
  font-size: 1rem;
  cursor: pointer;
  transition: all 0.2s;
}

.primary-button {
  background-color: #4a9eff;
  color: white;
}

.primary-button:hover {
  background-color: #3588e8;
  transform: translateY(-2px);
}

.secondary-button {
  background-color: rgba(255, 255, 255, 0.1);
  color: white;
}

.secondary-button:hover {
  background-color: rgba(255, 255, 255, 0.2);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .interest-preferences {
    padding: 1rem;
  }
  
  .tag-selection {
    flex-direction: column;
  }
  
  .experience-levels {
    flex-direction: column;
  }
  
  .experience-option {
    width: 100%;
  }
  
  .preferences-actions {
    flex-direction: column;
  }
  
  .primary-button,
  .secondary-button {
    width: 100%;
  }
}
</style>